const {
  insertAddress,
  getAddressList,
  getOneAddress,
  update2Address,
  remove2Address,
} = require("../service/contact.service");

class ContactController {
  // 创建联系人地址
  async createAddress(ctx, next) {
    const {
      contact_name,
      contact_phone,
      user_id,
      province,
      city,
      county,
      address_detail,
      is_default = "0",
    } = ctx.request.body;
    // // 操作数据库
    try {
      const result = await insertAddress(
        contact_name,
        contact_phone,
        user_id,
        province,
        city,
        county,
        address_detail,
        is_default
      );

      if (result) {
        ctx.response.body = {
          code: 200,
          message: "创建成功",
          data: true,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 查询联系人地址列表
  async gainAddressList(ctx, next) {
    const { user_id } = ctx.request.query;
    // // 操作数据库
    try {
      const result = await getAddressList(user_id);
      if (result) {
        ctx.response.body = {
          code: 200,
          message: "查询成功",
          data: result,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }
  // 查询单个联系人地址
  async gainOneAddress(ctx, next) {
    const { contact_id, user_id } = ctx.request.query;
    // // 操作数据库
    try {
      const result = await getOneAddress({ contact_id, user_id });
      if (result) {
        ctx.response.body = {
          code: 200,
          message: "查询成功",
          data: result,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 更新联系人地址
  async updateAddress(ctx, next) {
    const {
      contact_name,
      contact_phone,
      user_id,
      province,
      city,
      county,
      address_detail,
      is_default,
      contact_id,
    } = ctx.request.body;
    // // 操作数据库
    try {
      const result = await update2Address(
        contact_name,
        contact_phone,
        user_id,
        province,
        city,
        county,
        address_detail,
        is_default,
        contact_id
      );
      if (result) {
        ctx.response.body = {
          code: 200,
          message: "更新成功",
          data: true,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 删除联系人地址
  async removeAddress(ctx, next) {
    const { contact_id } = ctx.request.body;
    // // 操作数据库
    try {
      const result = await remove2Address(contact_id);
      if (result) {
        ctx.response.body = {
          code: 200,
          message: "删除成功",
          data: true,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new ContactController();
